//
//  BaseHttpHandler.m
//  MyCloud_OC
//
//  Created by ZEROLEE on 16/4/6.
//  Copyright © 2016年 laomi. All rights reserved.
//

#import "laomi_baseHttpHandler.h"
#import "AFNetworking.h"
#import "AFHTTPSessionManager.h"
#import "UIView+Toast.h"
#import "MBProgressHUD.h"

NSInteger const request_login_expire = 401;//登录过期
NSString * const request_status_key = @"status";//http请求keystatus
NSString * const request_data_key = @"result";//http 请求数据字
NSInteger const http_success_code = 200;
NSInteger const http_server_error_code = 500;
NSString *const msid_location_key = @"msid_location_key";//存储msid的key;
NSString * _Nullable const request_login_expire_notification = @"request_login_expire_notification"; // 登录超时通知
NSString * const api_init_sdk = @"/login";//登录;也是初始化的接口；去获取mSid;
NSString * const api_common_upload_file = @"/common/upload";//上传图片

@interface laomi_baseHttpHandler  ()



@end



@implementation laomi_baseHttpHandler
+(instancetype)shareInstance
{
    static laomi_baseHttpHandler *varInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        varInstance = [[laomi_baseHttpHandler alloc]init];
    });
    return varInstance;
}
+(void)laomi_hiddenHUD
{
    if ([[NSThread currentThread] isMainThread]) {
        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
        });
    }
    
}

+(MBProgressHUD*)laomi_showHud
{
    __block MBProgressHUD* varInstance = nil;
    if([[NSThread currentThread] isMainThread]){
        varInstance = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    }else{
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        dispatch_async(dispatch_get_main_queue(), ^{
            varInstance = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
            dispatch_semaphore_signal(semaphore);
        });
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    }
    return varInstance;
}


+(void)laomi_uploadFileFor:(LaomiRequestModel*)reqModel;
{
    NSString *url  = reqModel.url;
    AFHTTPSessionManager  * manager = [self sharedSessionManager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    for (NSString* key in [reqModel.header allKeys]) {
        [manager.requestSerializer setValue:reqModel.header[key]?reqModel.header[key]:@"" forHTTPHeaderField:key];
    }
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    if ([reqModel.method isEqualToString:@"POST"]) {
        
    }
#if DEBUG
    NSLog(@"url:%@,param:%@,header:%@",url,reqModel.param,reqModel.header);
#endif
    dispatch_queue_t queue2 = dispatch_queue_create("CONCURRENT", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue2, ^{
        [laomi_baseHttpHandler laomi_showHud];
    });
    [manager POST:url parameters:reqModel.param headers:reqModel.header constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:reqModel.uploadData?reqModel.uploadData:[NSData data] name:reqModel.uploadKey?reqModel.uploadKey:@"file" fileName:reqModel.uploadFileName?reqModel.uploadFileName:@"fileName.jpg" mimeType:reqModel.uploadFileType?reqModel.uploadFileType:@"jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (reqModel.progerss) {
            reqModel.progerss(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     #if DEBUG
               NSLog(@"responseObject:%@",responseObject);
       #endif
            [laomi_baseHttpHandler laomi_hiddenHUD];
               if ([NSJSONSerialization isValidJSONObject:responseObject]) {
                   if([responseObject[request_status_key] integerValue]==http_success_code)
                   {
                       if(reqModel.sucess){
                           reqModel.sucess(responseObject[request_data_key]);
                       }
                   }else if([responseObject[request_status_key] integerValue]==request_login_expire){
                       if(reqModel.failed){
                           reqModel.failed(responseObject);
                       }
                       if(reqModel.expireBlock){
                           reqModel.expireBlock(nil);
                       }
                   }else{
                       NSString *str = responseObject[@"message"];
                                      [self laomi_showToast:str];
                                      if(reqModel.failed){
                                          reqModel.failed(responseObject);
                                      }
                   }
               }else{
                    [laomi_baseHttpHandler laomi_hiddenHUD];
                   [self laomi_showToast:reqModel.networkErrorString];
                   if(reqModel.failed){
                       reqModel.failed(nil);
                   }
               }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
     #if DEBUG
               NSLog(@"error:%@",error);
       #endif
                [laomi_baseHttpHandler laomi_hiddenHUD];
               [self laomi_showToast:reqModel.networkErrorString];
               if(reqModel.failed){
                   reqModel.failed(nil);
               }
    }];
}

+(void)laomi_requestFor:(LaomiRequestModel*)reqModel;
{
    NSString *url  = reqModel.url;
    AFHTTPSessionManager  * manager = [self sharedSessionManager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    for (NSString* key in [reqModel.header allKeys]) {
        [manager.requestSerializer setValue:reqModel.header[key]?reqModel.header[key]:@"" forHTTPHeaderField:key];
    }
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    if ([reqModel.method isEqualToString:@"POST"]) {
        
    }
#if DEBUG
    NSLog(@"url:%@,param:%@,header:%@",url,reqModel.param,reqModel.header);
#endif
    if (reqModel.isNeedLoading) {
        dispatch_queue_t queue2 = dispatch_queue_create("CONCURRENT", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue2, ^{
            [laomi_baseHttpHandler laomi_showHud];
        });
    }
    [manager POST:url parameters:reqModel.param?reqModel.param:@{} headers:reqModel.header progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
#if DEBUG
        NSLog(@"responseObject:%@",responseObject);
#endif
         [laomi_baseHttpHandler laomi_hiddenHUD];
        if ([NSJSONSerialization isValidJSONObject:responseObject]) {
            if([responseObject[request_status_key] integerValue]==http_success_code)
            {
                if(reqModel.sucess){
                    reqModel.sucess(responseObject[request_data_key]);
                }
            }else if([responseObject[request_status_key] integerValue]==request_login_expire){
                if(reqModel.failed){
                    reqModel.failed(responseObject);
                }
                if(reqModel.expireBlock){
                    reqModel.expireBlock(nil);
                }
            }else{
                NSString *str = responseObject[@"message"];
                               [self laomi_showToast:str];
                               if(reqModel.failed){
                                   reqModel.failed(responseObject);
                               }
            }
        }else{
            [laomi_baseHttpHandler laomi_hiddenHUD];
            [self laomi_showToast:reqModel.networkErrorString];
            if(reqModel.failed){
                reqModel.failed(nil);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
#if DEBUG
        NSLog(@"error:%@",error);
#endif
        [laomi_baseHttpHandler laomi_hiddenHUD];
        [self laomi_showToast:reqModel.networkErrorString];
        if(reqModel.failed){
            reqModel.failed(nil);
        }
    }];
}

+(AFHTTPSessionManager*)sharedSessionManager;
{
    static AFHTTPSessionManager *varInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        varInstance = [AFHTTPSessionManager manager];
        //返回的数据格式为json 数据
        AFHTTPResponseSerializer *jsonSerial = [AFJSONResponseSerializer serializer];
        ((AFJSONResponseSerializer*)jsonSerial).removesKeysWithNullValues = YES;
        varInstance.responseSerializer = jsonSerial;
        [varInstance.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        varInstance.requestSerializer.timeoutInterval=20.0f;
        [varInstance.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        varInstance.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    });
    
    return varInstance;
}
+(NSString*)laomi_appendParam:(NSDictionary*)parm inGETURL:(NSString*)url;
{
    if (!parm) {
        return url;
    }else{
        __block NSString *urlafter = [NSString stringWithFormat:@"%@?", url];
        [parm enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            urlafter = [urlafter stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,obj]];
        }];
        return urlafter;
    }
}

+(void)laomi_showToast:(NSString*)string;
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication].keyWindow makeToast:string];
    });
}
@end
